package com.dhms.vostok1.utils

import android.util.Log
import com.dhms.vostok1.data.LocalUserInfoData
import com.dhms.vostok1.network.MoshiObject
import com.squareup.moshi.JsonAdapter
import com.tencent.mmkv.MMKV

/**
 * 用户信息
 * 存放 当前用户的信息
 * */
class UserInfoManager {
    companion object {
        const val TAG = "UserInfoManager"
        private const val UserInfoKey = "UserInfoKey"
        private val mmkv = MMKV.defaultMMKV()

        val token: String?
            get() {
                return userInfo?.token
            }

        val organizationId: Long?
            get() {
                return userInfo?.organizationId
            }

        val userId: Long?
            get() {
                return userInfo?.userId
            }

        var userInfo: LocalUserInfoData? = null
            set(value) {
                val jsonAdapter: JsonAdapter<LocalUserInfoData> =
                    MoshiObject.moshi.adapter(
                        LocalUserInfoData::class.java)
                val json = jsonAdapter.toJson(value)
                Log.i(TAG, "userInfo:$json")
                /*将json 数据存储到本地*/
                mmkv.encode(UserInfoKey, json)
                field = value
            }


        fun getLocalUserInfo(): LocalUserInfoData? {
            val jsonAdapter: JsonAdapter<LocalUserInfoData> =
                MoshiObject.moshi.adapter(
                    LocalUserInfoData::class.java)
            val json = mmkv.decodeString(UserInfoKey)
            Log.i(TAG, "getUserInfo:$json")
            return json?.let { jsonAdapter.fromJson(it) }
        }
    }
}